package com.example;

import com.example.pojo.Sx;
import com.example.pojo.Users;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/ws/{userId}/{title}")
@Component
@Slf4j
public class WebSocketServerEndpoint {

    // 用于存储用户ID和对应的WebSocket会话
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    private static String nowDate;
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, @PathParam("title") String title, Session session) {
        session.getUserProperties().put("userId", userId);
        session.getUserProperties().put("title", title);
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //格式转化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        nowDate = now.format(formatter);
        session.getUserProperties().put("date", nowDate);
        sessionMap.put(userId, session);
        log.info("WebSocket connection opened. User id: {}, Title: {},Date: {}", userId, title,nowDate);

//        broadcast("User '" + userId + "' joined the chat in channel '" + title + "'"+nowDate);
        broadcast(userId +"已经上线",title);

        // 发送已连接用户列表给新用户
        sendConnectedUsersToUser(userId,title);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Received message from session {}: {}", session.getId(), message);

        // 假设消息格式为 "userId:messageContent:channel"
        String[] parts = message.split("&:#", 3); // 分割成最多两部分
        if (parts.length == 3) {
            String userId = parts[0];
            String messageContent = parts[1];
            String title = parts[2];
            // 广播消息给所有客户端
            broadcast2(userId, messageContent, title,nowDate);
        } else {
            log.warn("Received message with unexpected format: {}", message);
        }
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId,@PathParam("title") String title, Session session) {
        sessionMap.remove(userId);
        log.info("下线: {}", userId);

        broadcast("User '" + userId + "' left the chat.",title);
    }

    // 广播消息给所有连接的用户
    private void broadcast(String message,String title) {
        sessionMap.forEach((userId, session) -> {
            try {
                // 检查接收者的频道信息
                String receiverTitle = (String) session.getUserProperties().get("title");
                if (receiverTitle != null && receiverTitle.equals(title)) {
                    session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                log.error("Error broadcasting message to user '{}'", userId, e);
            }
        });
    }
    private void broadcast2(String userId, String messageContent, String title,String nowDate) {
        sessionMap.forEach((sessionId, session) -> {
            try {
                // 检查接收者的频道信息
                String receiverTitle = (String) session.getUserProperties().get("title");
                if (receiverTitle != null && receiverTitle.equals(title)) {
                    String formattedMessage = String.format("%s&:#%s&:#%s&:#%s", userId, messageContent, title,nowDate);
                    session.getBasicRemote().sendText(formattedMessage);
                } else {
                    log.warn("Session '{}' does not match expected title '{}' date '{}'", sessionId, title,nowDate);
                }
            } catch (IOException e) {
                log.error("Error broadcasting message to session '{}': {}", sessionId, e.getMessage());
            }
        });
    }


    // 发送已连接用户列表给指定用户
    private void sendConnectedUsersToUser(String userId,String title) {
        // 筛选符合条件的用户列表
        String userListMessage = sessionMap.entrySet().stream()
                .filter(entry -> entry.getValue().getUserProperties().get("title").equals(title))
                .map(Map.Entry::getKey) // 获取用户ID
                .collect(Collectors.joining(" ", "Connected users: ", ""));
        // 获取目标用户的会话
        Session session = sessionMap.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(userListMessage);
            } catch (IOException e) {
                log.error("Error sending connected users list to user '{}'", userId, e);
            }
        }
    }
}
